<template>
  <div class="request-animation-frame">
    <div>
      <label>
        <span> requestAnimationFrame: </span>
        <progress :value="process" max="100" />
      </label>
    </div>
    <div>
      <label
        ><span>setInterval:</span> <progress :value="process2" max="100"
      /></label>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'

// 总共需要的时间 （s）
const needTime = 6
const hz = 60
const process = ref(0)
const process2 = ref(0)
const rafNumber = ref()
const timer = ref(null)
const lastTime = ref(0)
const animation = (time) => {
  if (!lastTime.value) lastTime.value = time
  const abs = Math.floor(((time - lastTime.value) / needTime) * 100) / 1000
  lastTime.value = time

  if (process.value >= 100) {
    console.timeEnd('a')
    process.value = 100
    cancelAnimationFrame(rafNumber.value)
    return
  }
  process.value += abs
  rafNumber.value = requestAnimationFrame(animation)
}
onMounted(() => {
  setTimeout(() => {
    console.time('a')
    console.time('b')
    rafNumber.value = requestAnimationFrame(animation)
    timer.value = setInterval(() => {
      if (process2.value >= 100) {
        console.timeEnd('b')
        clearInterval(timer.value)
        process2.value = 1000
        return
      }
      const abs = Math.floor((100 / hz / needTime) * 10000) / 10000
      console.log('setInterval', abs)

      process2.value += abs
    }, Math.floor(1000 / hz * 1000) / 1000)
  }, 2 * 1000)
})
</script>
<style lang="scss" scoped>
.request-animation-frame {
  label {
    span {
      width: 100px;
      font-size: 20px;
    }
    progress {
      width: 80vw;
      background-color: #fff;
    }
  }
}
</style>
